package simple.demo.springintegration.demo.chapter5;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.core.PollableChannel;
import org.springframework.integration.support.MessageBuilder;

public class E1App {
	private static final int COUNT = 1024 * 1024;
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("performance-service-activator.xml");
		context.start();
		
		MessageChannel input = (MessageChannel)context.getBean("input");
		final PollableChannel output = (PollableChannel)context.getBean("output");
		
		ExecutorService service = Executors.newSingleThreadExecutor();
		final CountDownLatch latch = new CountDownLatch(COUNT);
		service.execute(new Runnable() {
			
			@Override
			public void run() {
				for(int k=0; k<COUNT; ++k)
				{
					Message<?> msg = output.receive();
					msg.getPayload();
					latch.countDown();
				}
			}
		});
		service.shutdown();
		
		long begin = System.currentTimeMillis();
		
		for(int k=0; k<COUNT; ++k)
			input.send(MessageBuilder.withPayload(k).build());
		
		latch.await();
		long end = System.currentTimeMillis();
		System.out.println("Time for process " + COUNT + " messages : " + (end - begin));
	}

}
